package com.itcast.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itcast.pojo.Permission;
import com.itcast.pojo.Role;
import com.itcast.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;



import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;





    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        try {
            User user = userService.findByUserame(username);
            if (user==null){
                return null;
            }
            Set<Role> roles = user.getRoles();
            List<GrantedAuthority> list = new ArrayList<>();
            if (roles!=null&&roles.size()>0){
                for (Role role : roles) {
                    Set<Permission> permissions = role.getPermissions();
                    if (permissions!=null&&permissions.size()>0){
                        for (Permission permission : permissions) {
                           list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                        }
                    }
                }
            }
            org.springframework.security.core.userdetails.User securityUser = new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);


            return securityUser;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
